﻿using Mapster;
using PLC.Core.Entities;
using PLC.Interface.BaseUsers;
using System.Linq;
using System.Threading.Tasks;
using YWM.Application;
using YWM.Application.Linq.Extensions;
using YWM.Common.DataEncryptions;
using YWM.Common.Extensions;

namespace PCL.Application.BaseUsers.Services
{
    internal class BaseUserService : AsyncCrudService<BaseUser, BaseUserResultDto, long, BaseUserResultRequestDto, BaseUserCreateDto, BaseUserDto>, IBaseUserService
    {
        protected override IQueryable<BaseUser> CreateFilteredQuery(BaseUserResultRequestDto input)
        {
            IQueryable<BaseUser> queryable = base.CreateFilteredQuery(input)
                .WhereIf(!input.Account.IsNullOrWhiteSpace(), bu => bu.Account.Contains(input.Account))
                .WhereIf(!input.DisplayName.IsNullOrWhiteSpace(), bu => bu.DisplayName.Contains(input.DisplayName));
            return queryable;
        }

        public async Task<BaseUserResultDto> GetUser(string userName, string password)
        {
            string pwd = MD5Encryption.Encrypt(MD5Encryption.Encrypt(MD5Encryption.Encrypt(password)));
            BaseUser user = await Repository.FirstOrDefaultAsync(bu => bu.Account.Equals(userName) && bu.Password.Equals(pwd));
            if (user == null)
            {
                throw Oh("用户名或密码无效");
            }

            if (!user.IsActive)
            {
                throw Oh("该用户已被禁用");
            }
            BaseUserResultDto baseUserResultDto = user.Adapt<BaseUserResultDto>();
            return baseUserResultDto;
        }

        public override Task<BaseUserResultDto> Create(BaseUserCreateDto input)
        {
            input.Password = MD5Encryption.Encrypt(MD5Encryption.Encrypt(MD5Encryption.Encrypt("123456")));
            return base.Create(input);
        }

        public async Task ChangePassword(UserPasswordDto input)
        {
            if (!input.NewPassword.Equals(input.ConfirmPassword))
            {
                throw Oh("确认密码与新密码不一致");
            }
            BaseUser user = await Repository.FirstOrDefaultAsync(bu => bu.Id.Equals(input.Id));
            string oldPwd = MD5Encryption.Encrypt(MD5Encryption.Encrypt(MD5Encryption.Encrypt(input.OldPassword)));
            if (!oldPwd.Equals(user.Password))
            {
                throw Oh("旧密码不正确");
            }
            user.Password = MD5Encryption.Encrypt(MD5Encryption.Encrypt(MD5Encryption.Encrypt(input.NewPassword)));
            await Repository.InsertOrUpdateAndGetIdAsync(user);
        }
    }
}
